/**
 * @description: axios 封装对象
 * @fileName: axios.js
 * @author: Evan
 * @date: 2021-07-09 14:17:03
 * @version: V1.0.0
 */
import axios from 'axios'
import { getToken } from './store'
import i18n from '@/locales'
const { t } = i18n.global

// 常见Http错误状态码
const http_status_code: {
  [key: number]: string
} = {
  400: '请求错误(400)',
  401: '未授权，请重新登录(401)',
  403: '拒绝访问(403)',
  404: '请求出错(404)',
  405: '请求方法不允许(405)',
  406: '请求不接受(406)',
  408: '请求超时(408)',
  414: '请求 URL 过长(414)',
  500: '服务器错误(500)',
  501: '服务未实现(501)',
  502: '网关错误(502)',
  503: '服务不可用(503)',
  504: '网络超时(504)',
  505: 'HTTP 版本不受支持(505)'
}

const status_codes = Object.keys(http_status_code)

const server = axios.create({
  //请求基地址
  baseURL: '/'
  // timeout: 1000 * 100, // 超时时间
})

// 请求拦截
server.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截
server.interceptors.response.use(
  config => {
    // 处理响应数据
    return config
  },
  error => {
    let status = error.response?.status

    // 错误状态码统一处理
    if (status >= 400) {
      let result = error.response.data || {}
      error = {
        code: status,
        message:
          result.message ||
          t(`request_status.${status_codes.includes(String(status)) ? status : 'other'}`),
        data: null
      }
    }
    return Promise.reject(error)
  }
)

export default server
